/***************************************************************************
 *   Copyright (C) 2010 by Oleg Goncharov  *
 *   $EMAIL$                           *                          
 *                                                                         *
 *   This file is part of ChessVision.                                     *
 *                                                                         *
 *   ChessVision is free software; you can redistribute it and/or modify   *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/

#include "cfiguresvm.h"
#include <iostream>

namespace Chess {

bool CFigureSVM::DetectFigures(const cv::Mat& img, const CBoardCells& brd, CPosition& position) {
	CvMat sample;
	float responce;
	
	CalcAllFeatures(img, brd);
	
	for(int i = 0; i < 64; i++) {
		sample = Samples().row(i);
		
		responce = white.predict(&sample);
		if (responce > 0.0f) {
			position.Cell(i) = Chess::white;
			continue;
		}
		responce = black.predict(&sample);
		if (responce > 0.0f) {
			position.Cell(i) = Chess::black;
			continue;
		}
		position.Cell(i) = Chess::empty;
	}
	return true;
}

void CFigureSVM::TrainSample(const cv::Mat& img, const CBoardCells& brd, const CPosition& pos) {
	CalcAllFeatures(img, brd);
	SetClasses(pos);
	
	CvMat samples = Samples();
	CvMat samples_idx = SamplesIdx();
	cv::Mat_<float> classes_int;
	CvMat classes;
	
	classes = classes_int = Classes().clone();
	for(int i = classes_int.rows - 1; i >= 0; i--) 
		classes_int(i, 0) = (classes_int(i, 0) > 5.0f) ? 1.0f : -1.0f;
	
	white.train(&samples,  &classes, 0, &samples_idx);
		
	classes = classes_int = Classes().clone();
	for(int i = classes_int.rows - 1; i >= 0; i--) 
		classes_int(i, 0) = (classes_int(i, 0) < -5.0f) ? 1.0f : -1.0f;
		
	black.train(&samples, &classes,  0, &samples_idx); 
	
	UpdateHistory();
}

}
